package cn.wolfcode.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @ClassName TimeConsumeGatewayFilterFactory
 * @Author VCR
 * @Date 2021/12/23 20:44
 * @Version 1.0
 */
@Component
public class TimeConsumeGatewayFilterFactory extends AbstractGatewayFilterFactory<TimeConsumeGatewayFilterFactory.Config> {
    // 模仿TimeConsumeGatewayFilterFactory进行修改
    public static final String PARTS_KEY = "parts";

    public TimeConsumeGatewayFilterFactory() {
        super(TimeConsumeGatewayFilterFactory.Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList("parts");
    }

    public GatewayFilter apply(TimeConsumeGatewayFilterFactory.Config config) {
        return new GatewayFilter() {
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                // filter内即为前置逻辑
                System.out.println("前置");
                if (!config.parts) {
                    // 如果parts的值不为true则不统计时间
                    return chain.filter(exchange);
                }
                // 获取前置时间
                exchange.getAttributes().put("beginTime", new Date().getTime());

                return chain.filter(exchange).then(Mono.fromRunnable(new Runnable() {
                    @Override
                    public void run() {
                        // 后置逻辑
                        System.out.println("后置");
                        long beginTime = (long) exchange.getAttributes().get("beginTime");
                        System.out.println("共耗时:"+(new Date().getTime()-beginTime)+"ms");
                    }
                }));
            }

        };
    }

    public static class Config {
        private boolean parts;

        public Config() {
        }

        public boolean getParts() {
            return this.parts;
        }

        public void setParts(boolean parts) {
            this.parts = parts;
        }
    }
}
